package com.autoagent.ai_live_master.scriptGeneration.service.impl;

import com.autoagent.ai_live_master.common.model.Payload;
import com.autoagent.ai_live_master.common.utils.AgentClient;
import com.autoagent.ai_live_master.common.utils.KbClient;
import com.autoagent.ai_live_master.common.utils.OssUtil;

import com.autoagent.ai_live_master.scriptGeneration.Enum.FileStatusEnum;
import com.autoagent.ai_live_master.scriptGeneration.dto.ScriptFeaturesDTO;
import com.autoagent.ai_live_master.scriptGeneration.entity.MethodologyFile;
import com.autoagent.ai_live_master.scriptGeneration.entity.ScriptFeatureFile;
import com.autoagent.ai_live_master.scriptGeneration.entity.ScriptFeatures;
import com.autoagent.ai_live_master.scriptGeneration.mapper.ScriptFeatureFileMapper;
import com.autoagent.ai_live_master.scriptGeneration.mapper.ScriptFeaturesMapper;


import com.autoagent.ai_live_master.scriptGeneration.service.ScriptFeaturesService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Service
public class ScriptFeaturesServiceImpl implements ScriptFeaturesService {
    
    @Autowired
    private ScriptFeaturesMapper mapper;

    @Autowired
    private ScriptFeatureFileMapper scriptFeatureFileMapper;

    @Autowired
    private KbClient kbClient;

    @Autowired
    @Qualifier("scriptAgentClient")
    private AgentClient agentClient;

    @Autowired
    private OssUtil ossUtil;

    @Override
    public void addFeature(ScriptFeaturesDTO dto) {
        log.info("开始处理脚本特性添加 - 用户ID: {}", dto.getUserId());

        log.info("获取最新的Script_features");
        ScriptFeatures latestFeatures= mapper.getLatestByUserId(dto.getUserId());
        String scriptFeatures = latestFeatures != null ? latestFeatures.getScriptFeatures() : "";

        log.info("开始上传文件到OSS");
        String ossFilePath = null;
        ScriptFeatureFile scriptFeatureFile = new ScriptFeatureFile();
        try {
            // 上传文件到OSS
            ossFilePath = ossUtil.uploadLargeFile(dto.getFile());
            log.info("文件上传到OSS成功，下载路径: {}", ossFilePath);

            // 保存文件记录到script_feature_files表
            scriptFeatureFile.setUserId(dto.getUserId());
            scriptFeatureFile.setFileName(dto.getFile().getOriginalFilename());
            scriptFeatureFile.setFilePath(ossFilePath);
            scriptFeatureFile.setRemarks("话术特征文件");
            scriptFeatureFile.setStatus(FileStatusEnum.PROCESSING);
            scriptFeatureFileMapper.insert(scriptFeatureFile);
            log.info("文件记录保存成功，文件ID: {}", scriptFeatureFile.getId());

        } catch (Exception e) {
            log.error("文件上传到OSS失败", e);
            return;
        }

        try {
            log.info("上传文件到知识库");
            String fileId = kbClient.uploadFile(dto.getFile().getBytes(), dto.getFile().getOriginalFilename(),"id",null);
            log.info("上传文件id，{}", fileId);

            Map<String, String> stateMap = new HashMap<>();
            stateMap.put("script", scriptFeatures);
            stateMap.put("user_id", String.valueOf(dto.getUserId()));

            log.info("准备payload数据");
            Payload payload = Payload.builder()
                    .agentId(agentClient.getAgentId())
                    .userChatInput("分析话术特点")
                    .files(Collections.singletonList(new Payload.FileInfo(fileId, dto.getFile().getOriginalFilename(), null, null)))
                    .state(stateMap)
                    .build();

            log.info("调用Agent处理");
            String requestId = agentClient.chat_completions_async(payload);
            Long fileIdToUpdate = scriptFeatureFile.getId(); // 保存ID用于更新状态
            // 异步处理
            CompletableFuture.runAsync(() -> {
                try {
                    log.info("开始异步查询 agent 结果");
                    String newScriptFeatures = agentClient.chat_completions_async_polling(requestId);
                    log.info("异步查询 agent 结果成功，返回脚本特性：{}", newScriptFeatures);

                    ScriptFeatures newFeatures = new ScriptFeatures();
                    newFeatures.setUserId(dto.getUserId());
                    newFeatures.setScriptFeatures(newScriptFeatures);
                    mapper.insert(newFeatures);

                    // 更新文件状态为成功
                    ScriptFeatureFile update=new ScriptFeatureFile();
                    update.setId(fileIdToUpdate);
                    update.setStatus(FileStatusEnum.SUCCESS);
                    scriptFeatureFileMapper.updateById(update);
                    log.info("文件状态已更新为 SUCCESS");

                } catch (Exception e) {
                    log.error("异步调用 agent 处理失败", e);
                    // 更新文件状态为成功
                    ScriptFeatureFile update=new ScriptFeatureFile();
                    update.setId(fileIdToUpdate);
                    update.setStatus(FileStatusEnum.FAILED);
                    scriptFeatureFileMapper.updateById(update);
                    log.info("文件状态已更新为 FAILED");
                    throw new RuntimeException("异步调用 agent 处理失败: " + e.getMessage());
                }
            });
        } catch (Exception e) {
            log.error("脚本特性添加失败 - 用户ID: {}, 错误: {}", dto.getUserId(), e.getMessage(), e);
            // 如果知识库处理失败，但OSS上传成功，文件记录已保存，不需要回滚OSS文件
            throw new RuntimeException("脚本特性添加失败", e);
        }
    }

    @Override
    public Page<ScriptFeatures> getPageByUserId(Long userId, Integer pageNum, Integer pageSize) {
        log.info("分页获取用户的话术特征列表 - 用户ID: {}, 页码: {}, 每页大小: {}", userId, pageNum, pageSize);
        LambdaQueryWrapper<ScriptFeatures> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ScriptFeatures::getUserId, userId)
               .orderByDesc(ScriptFeatures::getId);
        Page<ScriptFeatures> page = new Page<>(pageNum, pageSize);
        return mapper.selectPage(page, wrapper);
    }

    @Override
    public ScriptFeatures getFeatureById(Long id) {
        log.info("根据ID获取话术特征 - ID: {}", id);
        return mapper.selectById(id);
    }

    @Override
    public Page<ScriptFeatureFile> getFilePageByUserId(Long userId, Integer pageNum, Integer pageSize, String keyword) {
        log.info("分页获取用户的话术特征文件列表 - 用户ID: {}, 页码: {}, 每页大小: {}, 关键字: {}", userId, pageNum, pageSize, keyword);

        Page<ScriptFeatureFile> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ScriptFeatureFile> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ScriptFeatureFile::getUserId, userId);

        // 如果有关键字，添加fileName字段的模糊匹配
        if (keyword != null && !keyword.trim().isEmpty()) {
            wrapper.like(ScriptFeatureFile::getFileName, keyword.trim());
        }

        // 按上传时间倒序排列
        wrapper.orderByDesc(ScriptFeatureFile::getUploadTime);

        return scriptFeatureFileMapper.selectPage(page, wrapper);
    }

    @Override
    public ScriptFeatureFile getFileById(Long id) {
        log.info("根据ID获取话术特征文件记录 - ID: {}", id);
        return scriptFeatureFileMapper.selectById(id);
    }
}